package PrefixSum;

//https://leetcode.cn/problems/matrix-block-sum/
public class l_1314 {
    public int[][] matrixBlockSum(int[][] mat, int k) {
        //这里注意下标转换, mat和ans矩阵都是0,0开始的, 而二位前缀和矩阵dp是1,1开始的, 计算时要转换
        int n = mat.length, m = mat[0].length;
        int[][] ans = new int[n][m];
        int[][] dp = new int[n + 1][m + 1];
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= m; j++)
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + mat[i - 1][j - 1]; //转换

        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
            {
                int x1 = Math.max(0, i - k);
                int y1 = Math.max(0, j - k);
                int x2 = Math.min(n - 1, i + k);
                int y2 = Math.min(m - 1, j + k);
                ans[i][j] = dp[x2 + 1][y2 + 1] - dp[x1][y2 + 1] - dp[x2 + 1][y1] + dp[x1][y1]; //转换
            }
        return ans;
    }
}
